﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using ZT.Core.Dto;
using ZT.Core.Service;

namespace ZT.Core.MiddleWare
{
    public class BaseController:ControllerBase
    {
        /// <summary>
        /// 当前请求的客户端IP
        /// </summary>
        public string ClientIP
        {
            get
            {

                var ip = this.HttpContext.Connection.RemoteIpAddress.ToString();
                if (!string.IsNullOrEmpty(ip) && IsIP(ip))
                {
                    return ip;
                }
                else
                {

                    return "127.0.0.1";
                }
            }
        }
        [NonAction]
        private static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        /// <summary>
        /// 服务
        /// </summary>
        public IList<object> Services { get; set; } = new List<object>();
        /// <summary>
        /// 进入系统的用户
        /// </summary>
        public AppUser AppUser { get; set; }


        /// <summary>
        /// 请求参数
        /// </summary>
        public string RequestParam { get; set; }
        /// <summary>
        /// 返回数据
        /// </summary>
        public string ResponseData { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Memo { get; set; }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="ex"></param>
        [NonAction]
        public void WriteLog()
        {
            var lg = AppUser == null ? "" : $"【用户名：{AppUser.UserInfo.Login},姓名：{AppUser.UserProfile.RelName}】";
            var d = ClientIP;
            var res =JObject.Parse(this.ResponseData);
                var log = new Model.Sys_Log
                {
                     RequestAction=this.HttpContext.Request.Path,
                     RequestMethod=this.HttpContext.Request.Method,
                     ResponseData=this.ResponseData,
                     RequestParam=this.RequestParam,
                     LogUser = lg,
                     OperateResult =Convert.ToInt32(res["State"]) == 200 ? true : false,
                     ClientIP = ClientIP,
                     Memo=this.Memo,
                     LogDate=DateTime.Now
                };
                ServiceBase obj = Services[0] as ServiceBase;
                var rpsLog = obj.UnitOfWork.Repository<Model.Sys_Log>();
                rpsLog.Insert(log);
                obj.UnitOfWork.Commit();
            }
        


    }
}
